<?php

require_once 'Zend/Config/Ini.php';
require_once 'Zend/Session/Namespace.php';
require_once 'Zend/Auth.php';

class Safe_LoginController extends Zend_Controller_Action
{
	private $_root;
	
    public function init()
    {
        parent::init();
		$auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity()) {
			//$this->identity = $auth->getIdentity();
			$this->_redirect('/');
		}
		$this->_root = dirname(dirname(__FILE__));
	}
	public function indexAction()
	{
		$cfg = new Zend_Config_Ini(CFG . DIRECTORY_SEPARATOR . 'config.ini', 'session');
		$this->view->cfg = $cfg;
		Zend_Session::setOptions($cfg->toArray());
		$defaultNamespace = new Zend_Session_Namespace();
		if (!isset($defaultNamespace->initialized)) {
			Zend_Session::regenerateId();
			$defaultNamespace->initialized = true;
		}
		$this->view->title = "Login";
		$this->view->form = $this->getForm();
	}

	private function getForm()
	{
		require_once $this->_root.'/forms/LoginForm.php';
		return new LoginForm(array(
		'action' => '/safe/login/post',
		'method' => 'post',
		));
	}
    function postAction()
    {
		$this->view->title = 'Login';
        $this->view->message = '';
		
		$request = $this->getRequest();
		if(!$request->isPost()) {
			$this->_helper->redirector('index');
		}else{
			// Get our form and validate it
			$form = $this->getForm();
			if(!$form->isValid($request->getPost())) {
				// Invalid entries
				$this->view->message = 'Invalid entries';
				$this->view->form = $form;
			}else{
				$formResult = $form->getValues();
				$identity	= $formResult['Alias'];
				$credential	= $formResult['Password'];
				
				# ...or configure the instance with setter methods
				$registry = Zend_Registry::getInstance();
				$dbAdapter = Zend_Db::factory($registry->config->database->adapter, $registry->config->database->params->toArray());
				
				require_once 'Zend/Auth/Adapter/DbTable.php';
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('accounts');
                $authAdapter->setIdentityColumn('alias');
                $authAdapter->setCredentialColumn('password');
				//$authAdapter->setCredentialTreatment('MD5(?)');
                
                // Set the input credential values to authenticate against
                $authAdapter->setIdentity($identity);
                $authAdapter->setCredential($credential);
                
                // do the authentication
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
				
                if ($result->isValid()) {
                    $data = $authAdapter->getResultRowObject(null,'password');
                    $auth->getStorage()->write($data);
					$authStore = $auth->getStorage()->read();
					
					$this->view->title = 'Welcome back '.$authStore->alias;
					$message = $result->getMessages();
                    $this->view->message = $message[0];
                } else {
                    // failure: clear database row from session
					$message = $result->getMessages();
					//$this->view->message = $message[0];
					$form->setDescription($message[0]);
					$this->view->form = $this->getForm();
                }
            }
        }
    } 
}
?>